# -*- coding: utf-8 -*-
#################################################################################
#
#    Copyright (c) 2015-Present Webkul Software Pvt. Ltd. (<https://webkul.com/>)
#
#################################################################################
from openerp.osv import fields, osv
from openerp.tools.translate import _

class product_template(osv.osv):
	_inherit = 'product.template'

	selection_list = [
		('consu', 'Consumable'),
		('service','Service')
		]
	def _get_virtual_stock(self, cr, uid, ids, names, args, context=None):
		res = {}
		qty_list = []
		virtual_qty = 0
		product_obj = self.browse(cr, uid, ids[0], context=context)
		if product_obj.type == 'service' and product_obj.is_pack:
			for pack_pdts in product_obj.wk_product_pack:
				orig_qty = pack_pdts.product_name.qty_available
				pack_qty = pack_pdts.product_quantity
				virtual_qty = orig_qty/pack_qty
				qty_list.append(virtual_qty)
			if len(qty_list) > 0:
				sorted_list = sorted(qty_list)
				res[product_obj.id] = sorted_list[0]	
			else:
				res[product_obj.id] = 0
		else:
			res[product_obj.id] = 0
		return res

	def _get_product_type(self, cr, uid, ids, field_names, args, context=None):
		res = {}
		return res

 	_columns = {
	'is_pack':fields.boolean('Is product pack'),
	'wk_product_pack':fields.one2many('product.pack','wk_product_template','Product pack'),
	'virtual_stock':fields.function(_get_virtual_stock, type = 'integer', string = "Virtual Stock"),
	'pack_stock_management':fields.selection([('decrmnt_pack','Decrement Pack Only'),('decrmnt_products','Decrement Products Only'),('decrmnt_both','Decrement Both')],'Pack Stock Management'),
	}

	def select_type_default_pack_mgmnt_onchange(self, cr, uid, ids, pk_dec,is_pack, context=None):
		if context is None:
			context = {}
		val = ''
		if is_pack:
			if pk_dec:
				if pk_dec == 'decrmnt_products':
					val = 'service'
				else:
					val = 'product'
			return {'value':{'type':val}}

	_defaults = {
	'pack_stock_management':'decrmnt_products',
	'type':'service'
	}

product_template()	

class product_product(osv.osv):
	_inherit = "product.product"

	def need_procurement(self, cr, uid, ids, context=None):
		for product in self.browse(cr, uid, ids, context=context):
			if product.type == 'service' and product.is_pack:
				return True
		return super(product_product, self).need_procurement(cr, uid, ids, context=context)

	def select_type_default_pack_mgmnt_onchange(self, cr, uid, ids, pk_dec,is_pack, context=None):
		if context is None:
			context = {}
		val = ''
		if is_pack:
			if pk_dec:
				self.pool.get('product.template').select_type_default_pack_mgmnt_onchange(cr, uid, ids,pk_dec,is_pack,context=context)
		return True
		
product_product()

class product_pack(osv.osv):
	_name = 'product.pack'
	_columns = {
		'product_name': fields.many2one('product.product','Product',required=True),
		'product_quantity':fields.float('Quantity',required = True),
		'wk_product_template':fields.many2one('product.template','Product pack'),
		'wk_image':fields.related('product_name','image_medium',type='binary',string='Image',store=True),
		'price':fields.related('product_name', 'lst_price', type='float', string='Product Price'),
		'uom_id':fields.related('product_name', 'uom_id', type='many2one', relation='product.uom', string="Unit of Measure", readonly="1"),
		'name':fields.related('product_name', 'name', type='char',readonly="1"),
		'description':fields.char('Description'),
		'delay': fields.integer('Leadtime'),
		}
	_defaults = {
			'product_quantity':1.0
		}
product_pack()

class sale_order(osv.osv):
	_inherit = 'sale.order'

	def action_ship_create(self, cr, uid, ids, context=None):
		context = context or {}
		vals = {}
		procurement_obj = self.pool.get('procurement.order')
		sale_line_obj = self.pool.get('sale.order').browse(cr, uid, ids)
		vals = super(sale_order, self).action_ship_create(cr, uid, ids, context=context)
		for order in self.browse(cr, uid, ids, context=context):
			proc_ids = []
			for line in order.order_line:
				if line.product_id.is_pack:
					line_data = self._prepare_order_line_procurement(cr, uid, order, line, order.procurement_group_id.id, context)
					if line.product_id.pack_stock_management != 'decrmnt_pack':
						for pack_obj in line.product_id.wk_product_pack:
							temp = line_data
							temp['product_id'] = pack_obj.product_name.id
							# temp['product_qty'] = line.product_uom_qty * pack_obj.product_quantity
							temp['product_qty'] = pack_obj.product_quantity
							temp['product_uom'] = pack_obj.product_name.uom_id.id
							temp['product_uos_qty'] = pack_obj.product_name.uos_id.id
							temp['sale_line_id'] = False
							ctx = context.copy()
							ctx['procurement_autorun_defer'] = True
							proc_id = procurement_obj.create(cr, uid, temp,ctx)
							proc_ids.append(proc_id)
				procurement_obj.run(cr, uid, proc_ids, context=context)		
		return vals
sale_order()

class sale_order_line(osv.osv):
	_inherit = 'sale.order.line'

	def product_id_change_with_wh(self, cr, uid, ids, pricelist, product, qty=0,
			uom=False, qty_uos=0, uos=False, name='', partner_id=False,
			lang=False, update_tax=True, date_order=False, packaging=False, fiscal_position=False, flag=False, warehouse_id=False, context=None):
		res = super(sale_order_line, self).product_id_change_with_wh( cr, uid, ids, pricelist, product, qty, uom, qty_uos, uos, name, partner_id, lang, update_tax, date_order,packaging, fiscal_position, flag, warehouse_id, context)
		warning = {}
		res_packing = self.product_packaging_change(cr, uid, ids, pricelist, product, qty, uom, partner_id, packaging, context=context)
		res['value'].update(res_packing.get('value', {}))
		warning_msgs = res_packing.get('warning') and res_packing['warning']['message'] or ''
		if product:
			product_obj = self.pool.get('product.product').browse(cr , uid , product, context=context)
			if product_obj.is_pack:
				for pack_product in product_obj.wk_product_pack:
					if qty * pack_product.product_quantity > pack_product.product_name.virtual_available:
						warn_msg = _('You plan to sell %s but you have only  %s quantities of the product %s available, and the total quantity to sell is  %s !!'%(qty, pack_product.product_name.virtual_available, pack_product.product_name.name,qty * pack_product.product_quantity)) 
						warning_msgs += _("Not enough stock ! : ") + warn_msg + "\n\n"
						if warning_msgs:
							warning = {
			                   'title': _('Configuration Error!'),
			                   'message' : warning_msgs
								}
						return {'warning': warning}
					
		return super(sale_order_line, self).product_id_change_with_wh( cr, uid, ids, pricelist, product, qty, uom, qty_uos, uos, name, partner_id, lang, update_tax, date_order,packaging, fiscal_position, flag, warehouse_id, context)

sale_order_line()

# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
